import os
import yaml
import logging
from logging.handlers import RotatingFileHandler
import datetime


def get_base_dir():
    """获取项目根目录"""
    return os.path.dirname(os.path.abspath(__file__))


def get_config_dir():
    """获取配置目录"""
    return os.path.join(get_base_dir(), "config")


def get_static_dir():
    """获取静态文件目录"""
    return os.path.join(get_base_dir(), "static")


def get_upload_dir():
    """获取上传文件目录"""
    return os.path.join(get_base_dir(), "uploads")


def get_log_dir():
    """获取日志目录"""
    return os.path.join(get_base_dir(), "logs")


def get_temp_dir():
    """获取临时目录"""
    return os.path.join(get_base_dir(), "temp")


def get_templates_dir():
    """获取模板目录"""
    return os.path.join(get_base_dir(), "templates")


def load_config():
    """加载配置文件"""
    config_path = os.path.join(get_config_dir(), "stream_conf.yaml")
    try:
        with open(config_path, "r", encoding="utf-8") as f:
            return yaml.safe_load(f)
    except Exception as e:
        logging.error(f"加载配置文件失败: {str(e)}")
        return {}


def setup_logger():
    """配置日志记录器"""
    logger = logging.getLogger("streaming_tool")
    logger.setLevel(logging.INFO)

    if not logger.handlers:
        log_dir = get_log_dir()
        if not os.path.exists(log_dir):
            os.makedirs(log_dir)
        current_date = datetime.datetime.now().strftime("%Y%m%d")

        log_path = os.path.join(log_dir, f"streaming_tool_{current_date}.log")
        file_handler = RotatingFileHandler(
            log_path,
            maxBytes=10 * 1024 * 1024,  # 10 MB
            backupCount=5,
            encoding="utf-8",
        )
        file_handler.setLevel(logging.INFO)

        console_handler = logging.StreamHandler()
        console_handler.setLevel(logging.INFO)

        formatter = logging.Formatter(
            "[%(asctime)s] [%(filename)s:%(lineno)s] [%(levelname)s]: %(message)s"
        )
        file_handler.setFormatter(formatter)
        console_handler.setFormatter(formatter)

        logger.addHandler(file_handler)
        logger.addHandler(console_handler)

    return logger
